package net.xepherx.ytdl;

import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import org.json.JSONObject;


public class Video {
	private final String imageBaseUrl = "http://i.ytimg.com/vi/%s/%d.jpg";
	private final String videoInfoUrl = "https://gdata.youtube.com/feeds/api/videos/%s?alt=json";
	
	private Image thumbnail;
	public Image getThumbnail(){return thumbnail;}
	public void setThumbnail(Image img){this.thumbnail = img;}
	
	private String url;
	private String videoId;
	String ApiUrlContent;
	String VideoHTML;
	
	private String uploader;
	private String title;
	private int lenInSec;
	
	public Video(String url) throws Exception{
		
		try {
			
			this.url = url;
			
			
			Pattern p = Pattern.compile("(?:\\?|&)v=([^&]*)");
			Matcher m = p.matcher(this.url);
			
			while(m.find()){
				videoId = m.group(1);
			}
			
			
			
			
			
			
			
			
			
			thumbnail = ImageIO.read(new URL(String.format(imageBaseUrl, videoId,1)));
			JSONObject videoData = new JSONObject(Utils.getUrlContent(new URL(String.format(videoInfoUrl, videoId))));
			title = videoData.getJSONObject("entry").getJSONObject("title").get("$t").toString();
			//uploader = videoData.getJSONObject("entry").getJSONOb).getString("$t");
			
			
			uploader = videoData.getJSONObject("entry").getJSONArray("author").getJSONObject(0).getJSONObject("name").get("$t").toString();
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new Exception("invalid url: "+e.getMessage());
		}
		
		
	}
	
	public String getUploader(){
		return this.uploader;
	}
	
	public String getTitle(){
		return this.title;
	}
}
